//
//  WebViewController.m
//  parity
//
//  Created by chuangjia on 23/9/15.
//  Copyright © 2015 lcb. All rights reserved.
//

#import "WebViewController.h"
#import "ZShare.h"
#import "viewconfig.h"
#import "ZToolsView.h"

#import "AppDelegate.h"
#import "UMengShare.h"
#import "LPPopup.h"
#import "NSString+Extensions.h"
#import "SVHTTPRequest.h"

#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"

#import "ZPlatformShare.h"

#import "ZToastManager.h"
#import "orderconfig.h"
#import "OrderInfo.h"
#import "ShopToolView.h"

#import "ZToolControl.h"
#import "CommentKeyBord.h"

#import "BaiChuanShare.h"
#import "UserNavigationController.h"
//JS交互
#import "JSCommentViewController.h"
#import "OtherUserCenterVC.h"
#import "OrderViewController.h"
#import "storageconf.h"
#import "ShaiDanVC.h"
#define DEFAULT_SHIPPING_FEE 39 //TODO : YINGGAI YUNDUAN SHUCHU

@interface WebViewController()<UIWebViewDelegate,NJKWebViewProgressDelegate, UIGestureRecognizerDelegate,UserDelegate>
{
    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
}


@property(nonatomic,strong) UIButton * shareButton;
@property(nonatomic,strong) UIWebView * webView;


@property(nonatomic,strong) ZToolControl *toolView;

@property(nonatomic,strong) ShopToolView *shoptoolView;
@property(nonatomic,strong) NSMutableArray *buyUrlArray;
@property(nonatomic,assign) BOOL isPostSever;

@property (nonatomic, strong)   NSDate* dateClickTime;//用户点击屏幕的时间点


@property(nonatomic,strong) OrderInfo *orderInfo;

@property(nonatomic,strong) NSString * strJsonData;
//@property(nonatomic,strong) NSString * strSkuJavascript;

@property(nonatomic,strong) NSString *JSBridge;
@property(nonatomic,strong) NSTimer* timerCheckPrice;

@property(nonatomic,assign) BOOL isSkuRequesting;
@property(nonatomic,assign) BOOL isSendRequest;
//
@property(nonatomic,strong) NSString *sharebtnText;
@property(nonatomic,strong) NSMutableDictionary *jsDictionary;
@property(nonatomic,assign) int commentFrom;
@property(nonatomic,assign) int selectQty;//是否有选者框
//
@property(nonatomic,assign) BOOL  ForceNewWindowOpen;
//
@property(nonatomic,strong)NSString *goods_from; //是否来自货架
@property(nonatomic,strong)NSString *comment_id; //是否来自货架
@property(nonatomic,strong)NSString *photo_id;

@property(nonatomic,strong) UIWebView * shortLinkWebView;
@property(nonatomic,strong)NSString *moneyUrl;//

@end

@implementation WebViewController

@synthesize baoliaoDictionary=_baoliaoDictionary;
@synthesize urlstr=_urlstr;
@synthesize titlestr=_titlestr;
@synthesize dikouquan=_dikouquan;
@synthesize shoptoolView=_shoptoolView;
@synthesize buyUrlArray=_buyUrlArray;
@synthesize isPostSever=_isPostSever;
@synthesize orderInfo=_orderInfo;
@synthesize sharebtnText=_sharebtnText;
@synthesize jsDictionary=_jsDictionary;
@synthesize commentFrom=_commentFrom;
@synthesize jsonUrl=_jsonUrl;
@synthesize selectQty=_selectQty;
@synthesize isSendRequest=_isSendRequest;
@synthesize shareDictionary=_shareDictionary;
@synthesize goods_from=_goods_from;
@synthesize comment_id = _comment_id;
@synthesize photo_id=_photo_id;
@synthesize shortLinkWebView=_shortLinkWebView;
@synthesize moneyUrl=_moneyUrl;
//=====================
//
//======================
-(void)jsonUrlHandler
{
    NSString *urlstr =[[NSString stringWithFormat:@"%@",_jsonUrl] replaceNullString];
    if (urlstr.length > 0)
    {
        __weak typeof (self) wSelf = self;
        [[SVHTTPClient sharedClient] GET:urlstr parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
        {
            if (response==nil||error!=nil)
            {
                return;
            }
            NSDictionary *dc =nil;
            if(response && [response isKindOfClass:[NSDictionary class]])
            {
                dc =(NSDictionary*)response;
            }else if (response && [response isKindOfClass:[NSString class]])
            {
                NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
                dc = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            }else if (response && [response isKindOfClass:[NSData class]])
            {
                dc = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil];
            }

            dispatch_async(dispatch_get_main_queue(), ^
            {
                if (dc && [dc isKindOfClass:[NSDictionary class]])
                {
                    _baoliaoDictionary = dc;
                  
                    if (_baoliaoDictionary)
                    {
                        _strSourceHTML = [_baoliaoDictionary objectForKey:@"post"];
                         self.goods_from = [_baoliaoDictionary objectForKey:@"goods_from"];
                        NSString *user_id =[ZShare sharedInstance].getUserId;
                        if (user_id.length>0) {
                            NSString *bodystr = [NSString stringWithFormat:@"<input type=\"hidden\" id=\"user_id\" value=\"%@\"></body>",user_id];
                            _strSourceHTML = [_strSourceHTML stringByReplacingOccurrencesOfString:@"</body>" withString:bodystr];
                        }
                    }
                   
                    
                    if (wSelf.baoliaoDictionary && [[wSelf.baoliaoDictionary allKeys] containsObject:@"coupon"])
                    {
                        NSString *coupon =[[NSString stringWithFormat:@"%@",[wSelf.baoliaoDictionary objectForKey:@"coupon"]] replaceNullString];
                        wSelf.dikouquan =coupon;
                        [ZShare sharedInstance].zhekouquan = coupon;
                       
                       
                    }
                    
                    NSString *buyUrl =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"money_url"]] replaceNullString] ;
                    self.moneyUrl = buyUrl;
                    [self shortlinkparser:buyUrl];
                    
                    NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
                    //判断下
                    if ([can_buy intValue]==1) {
                        [UMengShare event:CK_SEEHAITAO acc:1];
                    }
                    //统计页面
                    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                    [dict setValue:@"view_post" forKey:@"action"];
                    [dict setValue:_titlestr forKey:@"type"];
                    [dict setValue:can_buy forKey:@"can_buy"];
                    [dict setValue:_urlstr forKey:@"source"];
                    [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                        
                    } failure:^(NSError *error) {
                        
                    }];
                    
                    if (wSelf.baoliaoDictionary && [[wSelf.baoliaoDictionary allKeys] containsObject:@"share"])
                    {
                        self.shareDictionary =[NSMutableDictionary dictionaryWithDictionary:[wSelf.baoliaoDictionary objectForKey:@"share"]];
                    }
                    if (self.shareDictionary && [self.shareDictionary isKindOfClass:[NSDictionary class]])
                    {
                        _sharebtnText =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"btnText"]] replaceNullString];
                    }
                    else
                    {
                        _sharebtnText =@"分享";
                    }
                    
                    if([_strSourceHTML length] == 0)
                    {
                        [wSelf init3thWebsiteheaderView];
                        [wSelf init3thWebsiteWebView];
                    }
                    else
                    {
                        [wSelf initBaoliaoWebView];
                    }
                }
                
            });
            
        }];
    }
}
- (void) initBaoliaoWebView
{
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];//UIColorFromRGB(0xf5f5f5);
    if (_webView) {
        _webView.delegate=nil;
        [_webView removeFromSuperview];
        _webView=nil;
    }
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0 , self.view.frame.size.width, self.view.frame.size.height)];
    _webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: _webView];
    
    UIView* statusbar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
    statusbar.backgroundColor = [UIColor whiteColor];
    //  statusbar.alpha = 0.95f;
    [self.view addSubview:statusbar];
    statusbar=nil;
    //*/
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(PHOTO_FRAME_WIDTH, 20+PHOTO_TIME_PADDING, 40, 40);
    backButton.tag =0;
    [backButton setImage:[UIImage imageNamed:@"title_back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    backButton.layer.cornerRadius = 20;
    backButton.layer.masksToBounds = YES;
    backButton.backgroundColor = [UIColor whiteColor];
    backButton.alpha = 0.9;
    //
    //分享
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _shareButton.frame = CGRectMake(DEVICE_WIDTH - 56 - PHOTO_FRAME_WIDTH, 20+(60-20-30)/2, 56, 30);
    _shareButton.tag =2;
    //  _shareButton.hidden=YES;
    _shareButton.titleLabel.font=FONT(13);
    [_shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_shareButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    
    _shareButton.layer.cornerRadius = 20;
    _shareButton.layer.masksToBounds = YES;
    _shareButton.backgroundColor = [UIColor orangeColor];
    _shareButton.alpha = 0.9;
    
    //设置按钮偏移
    _shareButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _shareButton.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _shareButton.layer.borderColor = [UIColor whiteColor].CGColor;
    _shareButton.layer.borderWidth = 2;
    [_shareButton setTitle:_sharebtnText forState:UIControlStateNormal];
    [_shareButton addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_shareButton];
    
    [_shareButton sizeToFit];
    _shareButton.frame = CGRectMake(DEVICE_WIDTH - _shareButton.frame.size.width - PHOTO_TIME_PADDING ,
                                    20+PHOTO_TIME_PADDING,
                                    _shareButton.frame.size.width + 40,
                                    40);
    
    //
    if (_progressProxy) {
        _progressProxy.webViewProxyDelegate=nil;
        _progressProxy.progressDelegate=nil;
        _progressProxy=nil;
    }
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    _webView.scalesPageToFit =YES;//避免pc网页太大
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    //todo：
    CGRect barFrame = CGRectMake(0, 20 - 1, self.view.frame.size.width, 1);
    if (_progressView) {
        [_progressView removeFromSuperview];
        _progressView=nil;
    }
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:_progressView];
    _progressView.hidden = YES;
    
    if ([_urlstr isEqualToString:@"<null>"]) {
        _urlstr =@"";
    }
    
  //  NSString* strHTML = [self htmlForJPGImage:[UIImage imageNamed:@"loading.png"]];
  //  [self.webView stringByEvaluatingJavaScriptFromString:@"document.write('<p>加载中...</p>');"];
    
    if( [_strSourceHTML length] > 0)
    {
        
        [_webView loadHTMLString:_strSourceHTML baseURL:nil];
        _progressProxy.bNewWindow = YES;
        
    }else if([_urlstr length] > 0)
    {
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:_urlstr]];
        
        [_webView loadRequest:request];
    }
    if(_ForceNewWindowOpen)
    {
        _progressProxy.bNewWindow = YES;
    }
    

}


//以下代码用途是屏蔽 taobao:// 类似协议自动弹出
-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    _dateClickTime = [NSDate date];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    //你要做的操作写在这里
    _dateClickTime = [NSDate date];
    return NO;
}
- (void)resetData
{
    
    if(_orderInfo)
    {
        _orderInfo = nil;
    }
    _orderInfo = [[OrderInfo alloc]init];
    _strJsonData = @"";
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.isSkuRequesting = NO;
    self.isSendRequest =NO;
     [ZShare sharedInstance].zhekouquan = self.dikouquan;
    [self resetData];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    if (!_buyUrlArray) {
        _buyUrlArray = [[NSMutableArray alloc] init];
    }
    self.buyUrlArray = [ZShare sharedInstance].buyUrlArray;
    _isPostSever=NO;
    _commentFrom =0;
    if (_jsonUrl.length>0) {
        
        [UMengShare event:CK_WEB acc:1];
      
        [self jsonUrlHandler];
    }else
    {
        if (_baoliaoDictionary)
        {
            _strSourceHTML = [_baoliaoDictionary objectForKey:@"post"];
            self.goods_from = [_baoliaoDictionary objectForKey:@"goods_from"];
            NSString *buyUrl =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"money_url"]] replaceNullString] ;
            self.moneyUrl = buyUrl;
            [self shortlinkparser:buyUrl];
            NSString *user_id =[ZShare sharedInstance].getUserId;
            if (user_id.length>0) {
                NSString *bodystr = [NSString stringWithFormat:@"<input type=\"hidden\" id=\"user_id\" value=\"%@\"></body>",user_id];
                _strSourceHTML = [_strSourceHTML stringByReplacingOccurrencesOfString:@"</body>" withString:bodystr];
            }
          
          
            [UMengShare event:CK_WEB acc:1];
            NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
            //判断下
            if ([can_buy intValue]==1) {
                [UMengShare event:CK_SEEHAITAO acc:1];
            }
            //统计页面
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:@"view_post" forKey:@"action"];
            [dict setValue:_titlestr forKey:@"type"];
            [dict setValue:can_buy forKey:@"can_buy"];
            [dict setValue:_urlstr forKey:@"source"];
            [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                
            } failure:^(NSError *error) {
                
            }];
            
        }
        if (self.baoliaoDictionary && [[self.baoliaoDictionary allKeys] containsObject:@"share"])
        {
            self.shareDictionary =[NSMutableDictionary dictionaryWithDictionary:[self.baoliaoDictionary objectForKey:@"share"]];
        }
        if (self.shareDictionary && [self.shareDictionary isKindOfClass:[NSDictionary class]]) {
            _sharebtnText =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"btnText"]] replaceNullString];
        }else{
            _sharebtnText =@"分享";
        }
        if([_strSourceHTML length] == 0)
        {
            [self init3thWebsiteheaderView];
            [self init3thWebsiteWebView];
        }
        else
        {
            [self initBaoliaoWebView];
        }
        
    }
   
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    
    tapGestureRecognizer.delegate = self;
    //将触摸事件添加到当前view
    [self.webView addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer =nil;
    
    if (!_orderInfo) {
        _orderInfo = [[OrderInfo alloc] init];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateJS:) name:@"updatejs" object:nil];
}
-(void)updateJS:(NSNotification*)notification
{
    NSString *comment_js = notification.object;
    [self.webView stringByEvaluatingJavaScriptFromString:comment_js];
    if (self.toolView) {
        [self islike];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if( [self isDianshangPage] == YES)
    {
        //是电商页面，有可能是我们自己预制了dp618DATA字段， 也可能是我们注入JS产生的该字段
        if(_timerCheckPrice == nil)
        {
            _timerCheckPrice = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAdvanced:) userInfo:nil repeats:YES];
        }
    }
}
//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
   if(_timerCheckPrice)
    {
        //关闭定时器
        [_timerCheckPrice invalidate];
        
        _timerCheckPrice = nil;
    }
   
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
     [NSObject cancelPreviousPerformRequestsWithTarget:self];
    if(_timerCheckPrice)
    {
        //关闭定时器
        [_timerCheckPrice invalidate];
        
        _timerCheckPrice = nil;
    }
    // Dispose of any resources that can be recreated.
    //    NSLog(@"%s", __PRETTY_FUNCTION__);
    
}
-(void)dealloc
{
     [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [ZShare sharedInstance].zhekouquan =@"";
    if(_timerCheckPrice)
    {
        //关闭定时器
        [_timerCheckPrice invalidate];
        _timerCheckPrice = nil;
    }
    self.buyUrlArray =nil;
     _isPostSever = NO;
    if (_webView) {
        _webView.delegate=nil;
        [_webView removeFromSuperview];
        _webView=nil;
    }
    
    if (_progressProxy) {
        _progressProxy.webViewProxyDelegate=nil;
        _progressProxy.progressDelegate=nil;
        _progressProxy=nil;
    }
    
    
    self.JSBridge=nil;
    if( self.shoptoolView)
    {
        self.shoptoolView.actionBlock=nil;
        [self.shoptoolView removeFromSuperview];
        self.shoptoolView=nil;
    }
    
    if(self.toolView)
    {
        [self.toolView removeFromSuperview];
        self.toolView = nil;
    }
    if (_progressView) {
        [_progressView removeFromSuperview];
        _progressView=nil;
    }
    if (_shortLinkWebView) {
        _shortLinkWebView.delegate =nil;
        _shortLinkWebView = nil;
    }
    self.orderInfo = nil;
    
    [CommentKeyBord commentKeyboard].mDelegate=nil;
    [[CommentKeyBord commentKeyboard].mTextView resignFirstResponder];
    [[CommentKeyBord commentKeyboard].mTextView removeFromSuperview];
    [CommentKeyBord commentKeyboard].mTextView=nil;
    DLog(@"%s", __PRETTY_FUNCTION__);
}

#pragma mark - 顶部工具栏
//========================================
//顶部工具栏
//========================================


-(void)shareAction
{
    if(self.shareDictionary)
    {
        if (self.shareDictionary && [self.shareDictionary isKindOfClass:[NSDictionary class]]) {
             NSString *shareText =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"shareText"]] replaceNullString];
             NSString *title =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"title"]] replaceNullString];
             NSString *image =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"image"]] replaceNullString];
             NSString *desc =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"desc"]] replaceNullString];
             NSString *url =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"url"]] replaceNullString];
            NSMutableDictionary *share = [NSMutableDictionary dictionary];
            [share setValue:desc forKey: @"desc"];
            [share setValue:image forKey: @"image"];
            [share setValue:title forKey: @"title"];
            [share setValue:url forKey: @"url"];
            [[ZPlatformShare sharedInstance] shareView:self.view dict:share type:shareText];
        }
    }
    else
    {
        //TODO:
        //第三方网页， 也应该允许用户分享给他人。
        NSMutableDictionary *share = [NSMutableDictionary dictionary];
        NSString* strTitle = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        [share setValue:strTitle forKey: @"desc"];
        [share setValue:@"好单品，要分享" forKey: @"title"];
        NSString* strURL = [_webView stringByEvaluatingJavaScriptFromString:@"document.location"];
        // _webView.request.URL.absoluteString;
        if (strURL.length==0) {
            strURL = _urlstr;
        }
        [share setValue:strURL forKey: @"url"];
        [[ZPlatformShare sharedInstance] shareView:self.view dict:share type:@"分享，是一种快乐。"];
    }

   
}

-(void)init3thWebsiteheaderView
{
    //
    UIView *headerView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    headerView.backgroundColor=[UIColor clearColor];
    
    UIImageView *backView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
    backView.image =[UIImage imageNamed:@"titile_bg.png"];
    [headerView addSubview:backView];
    backView=nil;
    
    UILabel *titleLabel =[[UILabel alloc] initWithFrame:CGRectMake(54, 20+(60-20-20)/2, self.view.frame.size.width-54*2, 20)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = UIColorFromRGB(0x808080);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT(16);
    titleLabel.text= @"";
    [headerView addSubview:titleLabel];
    titleLabel=nil;
    //
    
    //后退按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20+(60-20-40)/2, 40, 40);
    backButton.tag =0;
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:backButton];
    
    
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    closeButton.frame = CGRectMake(40 + PHOTO_TIME_PADDING, 20+(60-20-40)/2, 40, 40);
    closeButton.tag =9;
    [closeButton setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:closeButton];
    
  //  if (self.baoliaoDictionary)
    //不管是不是爆料，都要显示 分享 按钮啊！ 最差分享一个amazon的链接
  //  {
        //分享
        _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _shareButton.frame = CGRectMake(DEVICE_WIDTH - 56 - PHOTO_FRAME_WIDTH, 20+(60-20-30)/2, 56, 30);
        _shareButton.tag =2;
        _shareButton.titleLabel.font=FONT(14);
        [_shareButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_shareButton setImage:[UIImage imageNamed:@"title_share"] forState:UIControlStateNormal];
        if (self.shareDictionary && [self.shareDictionary isKindOfClass:[NSDictionary class]]) {
            _sharebtnText =[[NSString stringWithFormat:@"%@",[self.shareDictionary objectForKey:@"btnText"]] replaceNullString];
        }else{
            _sharebtnText =@"  分享";
        }
        [_shareButton setTitle:_sharebtnText forState:UIControlStateNormal];
        [_shareButton addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:_shareButton];
        
        [_shareButton sizeToFit];
        _shareButton.frame = CGRectMake(DEVICE_WIDTH - _shareButton.frame.size.width - PHOTO_FRAME_WIDTH, 20+(60-20-30)/2, _shareButton.frame.size.width, 30);
    
    
  //  }
   
    CGRect barFrame = CGRectMake(0, 60 - 1, self.view.frame.size.width, 1);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [headerView addSubview:_progressView];
    _progressView.hidden = YES;
    
    [self.view addSubview:headerView];
    headerView=nil;
    
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    if(_progressView.hidden == YES)
        _progressView.hidden = NO;
    [_progressView setProgress:progress animated:YES];
}

-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton *)sender;
    switch (btn.tag) {
        case 0:
        {
             [NSObject cancelPreviousPerformRequestsWithTarget:self];
            if(_timerCheckPrice)
            {
                //关闭定时器
                [_timerCheckPrice invalidate];
                _timerCheckPrice = nil;
            }
            if ([self.webView canGoBack])
            {
                [self.webView goBack];
                
                break;
            }
            if (_shortLinkWebView) {
                _shortLinkWebView.delegate =nil;
                _shortLinkWebView = nil;
            }
            [ZShare sharedInstance].zhekouquan =@"";
            if (self.navigationController)
            {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 1: //复制链接
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            [pasteboard setString:_urlstr];
            LPPopup *popup = [LPPopup popupWithText:@"链接地址已复制到粘帖板！"];
            [popup showInView:self.view
                centerAtPoint:self.view.center
                     duration:kLPPopupDefaultWaitDuration
                   completion:nil];
        }
            break;
            
        case 9: //关闭
        {
            [ZShare sharedInstance].zhekouquan =@"";
            if (self.navigationController)
            {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        default:
            break;
    }
}

-(BOOL) isLocalHtmlContent
{
    
    if([_strSourceHTML length] > 0)
    {
        return YES;
    }
    return NO;
}
-(BOOL)webViewNewWindow:(NSURLRequest *)request;
{
//    if([request.URL.absoluteString isEqual:@"http://www.mgpyh.com/"])
//        return NO;
    NSString *buyUrl =[[NSString stringWithFormat:@"%@",request.URL.absoluteString] replaceNullString] ;
    if (buyUrl.length != 0)
    {
        WebViewController *shaidanweb =[[WebViewController alloc] init];
        shaidanweb.titlestr=_titlestr;
        shaidanweb.urlstr =buyUrl;
        shaidanweb.dikouquan = self.dikouquan;
        shaidanweb.shareDictionary =self.shareDictionary;
        [ZShare sharedInstance].zhekouquan = self.dikouquan;
        [self.navigationController pushViewController:shaidanweb animated:YES];
        shaidanweb=nil;
    }
    
    return YES;
}

-(void)webViewShowFooter:(BOOL) show  buySupport:(BOOL) buy  url:(NSString*)strURL html:(NSString*)strHTML
{
    if(show == NO)
    {
        return;
    }
    
    [self inttoolView];
}


//===================================
// 底部工具栏
//===================================
-(void)inttoolView
{
    NSString* webType = [[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"is_subject"]] replaceNullString];
    if ([webType isEqualToString:@"true"] || [webType intValue]==1) {
        _webView.frame = CGRectMake(0, 0 , self.view.frame.size.width, self.view.frame.size.height);
        return;
    }
    if (_toolView) {
        [_toolView removeFromSuperview];
        _toolView=nil;
    }
    _toolView =[[ZToolControl alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-40, self.view.frame.size.width, 40)];
    if( [_strSourceHTML length] > 0){
        _toolView.buyTitle =@"去购买";
    } else{
        _toolView.buyTitle =@"一键海淘";
    }
    if (_baoliaoDictionary) {
        NSString *comment_count =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"comment_count"]] replaceNullString];
        if ([comment_count intValue]>0) {
            _toolView.commentCount = comment_count;
        }
        
        NSString *is_like =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"is_liked"]] replaceNullString];
        if ([is_like intValue]==0) {
            _toolView.isLove = NO;
        }else{
            _toolView.isLove = YES;
        }
        [self islike];
    }
    __weak typeof (self) wSelf = self;
    [_toolView setCallBack:^(ZToolControlType type, UIView *v, id k, id va) {
        [wSelf callback:type view:v k:k va:va];
    }];
    [self.view addSubview:_toolView];
    _webView.frame = CGRectMake(0, 0 , self.view.frame.size.width, self.view.frame.size.height-40);
}
-(void)callback:(ZToolControlType)type view:(UIView*)v k:(id)k va:(id)va
{
    switch (type) {
        case ZToolControlType_unknow:
        {
            
        }
            break;
        case ZToolControlType_comment:
        {
            if ([self isLogin]) {
                _commentFrom=1;
                [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
            }
        }
            break;
        case ZToolControlType_commentlist:
        {
            NSString*postid =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"id"]] replaceNullString];
            NSString*goodfrom = [_baoliaoDictionary objectForKey:@"goods_from"];
            if ([goodfrom isEqualToString:@"huojia"]) {
                StorageCommentViewController *comm =[[StorageCommentViewController alloc] init];
                comm.commentId =postid;
                [self.navigationController pushViewController:comm animated:YES];
                return;
            }else{
                JSCommentViewController *jscomment = [[JSCommentViewController alloc] init];
                jscomment.commentId =postid;
                jscomment.content_object =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"resource_uri"]] replaceNullString];
                [self.navigationController pushViewController:jscomment animated:YES];
                jscomment=nil;
            }
           
            return;
        }
            break;
        case ZToolControlType_like:
        {
             if ([self isLogin]) {
                NSString*pid =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"id"]] replaceNullString];
                 NSString*goodfrom = [_baoliaoDictionary objectForKey:@"goods_from"];
                 if ([goodfrom isEqualToString:@"huojia"]) {
                    if(pid.length>0)
                     {
                         [UMengShare event:CK_LOVE acc:1];
                         NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                         [dict setValue:pid forKey:@"photo_id"];
                         [BaseModel love:dict success:^(AFHTTPRequestOperation *operation, id result) {
                             int code =  [[result objectForKey:@"code"] intValue];
                             if (code==1) {
                                 _toolView.isLove = YES;
                             }else
                             {
                                 _toolView.isLove = NO;
                             }
                             
                         } failure:^(NSError *error) {
                             _toolView.isLove = NO;
                         }];
                     }
                 }else{
                     NSString *resource_uri =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"resource_uri"]] replaceNullString];
                     [self likeWithPid:pid resource_uri:resource_uri];
                 }
               
             }
            
        }
            break;
        case ZToolControlType_buy:
        {
             NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
            //判断下
            if ([can_buy intValue]==1) {
                _titlestr=[NSString stringWithFormat:@"%@_baoliao",_titlestr];
                [UMengShare event:CK_GOBUYHAITAO acc:1];
            }else{
                
                [UMengShare event:CK_GOBUY acc:1];
            }
            //去购买的统计页面
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:@"view_post_click_buy" forKey:@"action"];
            [dict setValue:_titlestr forKey:@"type"];
            [dict setValue:can_buy forKey:@"can_buy"];
            [dict setValue:_urlstr forKey:@"source"];
            [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                
            } failure:^(NSError *error) {
                
            }];
             if ([self.goods_from isEqualToString:@"huojia"])
             {
                 id  buy_action_js =[_baoliaoDictionary objectForKey:@"buy_action_js"];
                 if (buy_action_js && [buy_action_js isKindOfClass:[NSString class]]) {
                     [_webView stringByEvaluatingJavaScriptFromString:buy_action_js];
                 }
                 return;
             }else
             {
                 NSString *baichuan_link =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"baichuan_link"]] replaceNullString] ;
                 if (baichuan_link && baichuan_link.length>0) {
                     [UMengShare event:CK_BUYBAICHUAN acc:1];
                     [[BaiChuanShare sharedInstance] showPage:self isNeedPush:YES openUrl:baichuan_link];
                     return;
                 }else
                 {
                     
                     NSString *buyUrl =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"money_url"]] replaceNullString] ;
                     NSString *coupon =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"coupon"]] replaceNullString] ;
                     
                     if (buyUrl.length != 0)
                     {
                         WebViewController *shaidanweb =[[WebViewController alloc] init];
                         shaidanweb.titlestr=_titlestr;
                         shaidanweb.urlstr =self.moneyUrl;
                         shaidanweb.dikouquan =coupon;
                         shaidanweb.shareDictionary =self.shareDictionary;
                         [ZShare sharedInstance].zhekouquan = coupon;
                         [self.navigationController pushViewController:shaidanweb animated:YES];
                         shaidanweb=nil;
                         
                     }
                     return;
                 }
                
                 return;
             }
           
            return;
        }
            break;
        case ZToolControlType_haitao:
        {
            //判断下
            [UMengShare event:CK_GOBUYHAITAO acc:1];
            if ([_titlestr isEqualToString:@"search"]) {
                [UMengShare event:CK_SEARCHHAITAO acc:1];
            }
            NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
            //去购买的统计页面
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:@"view_post_click_buy" forKey:@"action"];
            [dict setValue:_titlestr forKey:@"type"];
            [dict setValue:can_buy forKey:@"can_buy"];
            [dict setValue:_urlstr forKey:@"source"];
            [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                
            } failure:^(NSError *error) {
                
            }];
            
            NSString *buyUrl =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"money_url"]] replaceNullString] ;
            NSString *coupon =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"coupon"]] replaceNullString] ;

            if (buyUrl.length != 0)
            {
                WebViewController *shaidanweb =[[WebViewController alloc] init];
                shaidanweb.titlestr =[NSString stringWithFormat:@"%@_baoliao",_titlestr];
                shaidanweb.urlstr =self.moneyUrl;
                shaidanweb.dikouquan =coupon;
                shaidanweb.shareDictionary =self.shareDictionary;
                [ZShare sharedInstance].zhekouquan = coupon;
                [self.navigationController pushViewController:shaidanweb animated:YES];
                shaidanweb=nil;
                
            }
        }
            break;
        default:
            break;
    }
}



- (BOOL) isUserClicked
{
    if(_dateClickTime == nil)
        return  NO;
    
    NSDate *now = [NSDate date];
    NSTimeInterval duration = [now timeIntervalSinceDate:_dateClickTime];
    
    
    if( duration < 1 )// || (application.applicationIconBadgeNumber  && strPushToken))
    {
        return YES;
    }
    
    return NO;
}

- (void) AmazonInfo:(NSString*)str
{
    
    //有JS输出数据
    
    if(self.toolView)
    {
        [self.toolView removeFromSuperview];
        self.toolView = nil;
    }
    
    if(self.shoptoolView == nil)
    {
        [self showShopToolView:@""];
    }
    
    
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    
    if([_strJsonData isEqual:str])
    {
        return;
    }
    
    _strJsonData = str;
    

//    NSLog(@"strJson: %@", _strJsonData);
    
    NSString *info  = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if(info == nil)
    {
         NSLog(@"info is nil! 解析云端的js数据失败！");
        return;
    }
    NSData* data = [info  dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    if(dcRes == nil)
    {
        NSLog(@"NSDictionary is nil. 解析云端的js数据失败！");
        return;
    }

    NSString* strErr;
 
    for (NSString *key in dcRes)
    {
        NSLog(@"key: %@ value: %@", key, dcRes[key]);
        
        if([key  isEqual: @"err_msg"])
        {
            
            strErr = dcRes[key];
            [self resetData];
        }
        else if([key  isEqual: @"totalPrice"])
        {
            _orderInfo.fTotalPrice = [dcRes[key] floatValue];
        }
        else if([key  isEqual: @"skuID"])
        {
            _orderInfo.strSkuID = dcRes[key];
        }
        else if([key  isEqual: @"shipFeeLocal"])
        {
            _orderInfo.fFareFeeUSA = [dcRes[key] floatValue];
        }
        else if([key  isEqual: @"taxPrice"])
        {
            _orderInfo.taxPrice = [dcRes[key] floatValue];
        }
        else if([key  isEqual: @"shipFeeOverseas"])
        {
           _orderInfo.fFareFee = [dcRes[key] floatValue];
        }
        else if([key  isEqual: @"price"])
        {
            _orderInfo.fPrice = [dcRes[key] floatValue];
        }else if ([key isEqual:@"conversionFee"])
        {
            _orderInfo.conversionFee = [dcRes[key] floatValue];
        }
        else if([key  isEqual: @"shippingWeight"])
        {
            _orderInfo.fPounds = [dcRes[key] floatValue];
        }
        else if([key  isEqual: @"weightUnit"])
        {
            //单位
        }
        else if([key isEqual:@"dimsInfo"])
        {
            _orderInfo.strDim = dcRes[key];
        }
        else if([key isEqual:@"cartInfo"])
        {
            _orderInfo.strPa = dcRes[key];
        }
        else if([key  isEqual: @"maxQty"])
        {
            _orderInfo.maxQty = [dcRes[key] intValue];
        }
        else if([key  isEqual: @"qty"])
        {
            _orderInfo.nQty = [dcRes[key] intValue];
        }
        else if([key  isEqual: @"image"])
        {
            _orderInfo.strProductImageURL = dcRes[key];
        }
        else if([key  isEqual: @"title"])
        {
            _orderInfo.strProduct = dcRes[key];
        }else if ([key isEqualToString:@"selectQty"])
        {
            _selectQty =[dcRes[key] intValue];
        }
        else if([key  isEqual: @"enable"])
        {
            if([dcRes[key] intValue])
            {
                [_shoptoolView EnableBuyButton:YES];
                [self enablebuy];
            }else{
                [self resetData];
                [_shoptoolView EnableBuyButton:NO];
            }
        }
    }
    
    
    _shoptoolView.priceStr = _orderInfo.fPrice > 0 ? [NSString stringWithFormat:@"%.0f",   _orderInfo.fTotalPrice] : @"" ;
    if(_orderInfo.fPrice > 0)
    {
        _shoptoolView.fareStr = (_orderInfo.fFareFee + _orderInfo.fFareFeeUSA) > 0 ? [NSString stringWithFormat:@"%.0f",   (_orderInfo.fFareFee + _orderInfo.fFareFeeUSA) ] : @"";
        _shoptoolView.taxStr = _orderInfo.taxPrice > 0 ? [NSString stringWithFormat:@"%.0f",   _orderInfo.taxPrice] : @"" ;
        [_shoptoolView setNumViewCount:[NSString stringWithFormat:@"%d",_orderInfo.nQty] maxQty:self.orderInfo.maxQty];
        
        if(_selectQty)
            [_shoptoolView setQtyStr: _orderInfo.fPrice > 0 ? [NSString stringWithFormat:@"( %d个 △ )",   _orderInfo.nQty]: @"" ];
        else
            [_shoptoolView setQtyStr: _orderInfo.fPrice > 0 ? [NSString stringWithFormat:@"( %d个 )",   _orderInfo.nQty]: @"" ];
            
        [_shoptoolView EnableBuyButton:YES];
        [self enablebuy];
        
        _shoptoolView.enableQtySelect = _selectQty;
   
    }
    else
    {
        [self resetData];
        [_shoptoolView EnableBuyButton:NO];
     
        if(strErr && [strErr length] > 0)
        {
             [_shoptoolView setAlertStr: strErr ];
        }
    }
    NSLog(@"AmazonInfo\n%@", dcRes);
}
-(void)enablebuy
{
    if ( self.isSendRequest==NO) {
        
        [UMengShare event:CK_SEARCHYES acc:1];
      
        self.isSendRequest=YES;
        NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
        //去购买的统计页面
        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
        [dict setValue:@"buypagecanpay" forKey:@"action"];
        [dict setValue:_titlestr forKey:@"type"];
        [dict setValue:can_buy forKey:@"can_buy"];
        [dict setValue:_urlstr forKey:@"source"];
        [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
            
        } failure:^(NSError *error) {
            
        }];
    }
  
}
#pragma mark - 中间网页视图
//========================================
//中间网页视图
//========================================
-(void)init3thWebsiteWebView
{
    float fWebViewHeight = self.view.frame.size.height-60 ;
    if (_webView) {
        _webView.delegate=nil;
        [_webView removeFromSuperview];
        _webView=nil;
    }
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 60 , self.view.frame.size.width, fWebViewHeight)];
    _webView.scalesPageToFit =YES;//避免pc网页太大
    if (_progressProxy) {
        _progressProxy.webViewProxyDelegate=nil;
        _progressProxy.progressDelegate=nil;
        _progressProxy=nil;
    }
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    [self.view addSubview: _webView];
 
    if(_ForceNewWindowOpen)
    {
        _progressProxy.bNewWindow = YES;
    }
//    NSString* strHTML = [self htmlForJPGImage:[UIImage imageNamed:@"loading.gif"]];
    NSString * strHTML = [NSString stringWithFormat: @"document.write('<div style=\"text-align:center;padding:15px;\">路途遥远，<br>请耐心等待...<br><br>长时间没反应？<br><a href=\"%@\">点此直接访问</a></div>');", _urlstr];
    [self.webView stringByEvaluatingJavaScriptFromString:strHTML];
    
   // [self.webView stringByEvaluatingJavaScriptFromString:@"document.write('<p>加载中...</p>');"];
  
    _urlstr = [[NSString stringWithFormat:@"%@",_urlstr] replaceNullString];
    if([_urlstr length] > 0)
    {
        [UMengShare event:CK_WEB_SEC acc:1];
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:_urlstr]];
        [_webView loadRequest:request];
    }
   
}
- (void)timerAdvanced:(NSTimer *)timer//这个函数将会执行一个循环的逻辑
{
    if([self isDianshangPage] == NO)
    {
        //用户已经离开了 商品详情界面
        
        if(_timerCheckPrice)
        {
            //关闭定时器
            [_timerCheckPrice setFireDate:[NSDate distantFuture]];
            
            
            [_timerCheckPrice invalidate];
            
            _timerCheckPrice = nil;
            
            
            [self resetData];
            
            if(_shoptoolView)
            {
                [_shoptoolView EnableBuyButton:NO];
            }
        }
    }
    else
    {
       
        
        [self.webView stringByEvaluatingJavaScriptFromString:@"dpCheckPrice()"];
        
        NSString *strJson = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('dp618DATA').value" ]];
        if ([strJson length] > 0)
        {
            _orderInfo.strJson = strJson;
            [self AmazonInfo:strJson];
            
        }

    }
    
    
    return;
    

}

-(BOOL) collectionWebViewHtml:(UIWebView*)webView
{
    
    BOOL ret = NO;
    NSString  *strUrl =webView.request.mainDocumentURL.absoluteString;
    _urlstr =strUrl;
 
    if (strUrl==nil || strUrl.length==0) {
        return ret;
    }
    if (!_isPostSever)
    {
        if ([self isShowBuyTool:strUrl])
        {
            //去购买的统计页面
            NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:@"buypage" forKey:@"action"];
            [dict setValue:strUrl forKey:@"source"];
            [dict setValue:_titlestr forKey:@"type"];
            [dict setValue:can_buy forKey:@"can_buy"];
            [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                
            } failure:^(NSError *error) {
                
            }];
            
            [self showShopToolView:@""];
            
            _isPostSever = YES;
        }
    }
    
    if ([self isShowBuyTool:strUrl] && _JSBridge.length>0)//todo:域名，js 判断页面是否有对应的js
    {
            if([self isDianshangPage] == NO)
            {
                [webView stringByEvaluatingJavaScriptFromString:@"var div = document.createElement('input');"
                 "div.id = 'danpin_dianshang_page_flag';"
                 "div.type = 'hidden';"
                 "div.value = 'I love danpin.com';"
          //       "div.style.display = 'none';"
                 "document.body.appendChild(div);"];
                
                _JSBridge = [_JSBridge stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                
                _JSBridge = [_JSBridge stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                _JSBridge = [_JSBridge stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                [self.webView stringByEvaluatingJavaScriptFromString:_JSBridge];
                
                NSLog(@"注入js代码成功！");
                //去购买的统计页面
                
                NSString *can_buy =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:@"buypagejs" forKey:@"action"];
                [dict setValue:strUrl forKey:@"source"];
                [dict setValue:_titlestr forKey:@"type"];
                [dict setValue:can_buy forKey:@"can_buy"];
                [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                    
                } failure:^(NSError *error) {
                    
                }];
                
                ret = YES;
            }
    }

    
    if( [self isDianshangPage] == YES)
    {
        //是电商页面，有可能是我们自己预制了dp618DATA字段， 也可能是我们注入JS产生的该字段。
        //是大是大非
        if(_timerCheckPrice == nil)
        {
            _timerCheckPrice = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAdvanced:) userInfo:nil repeats:YES];
        }
    
        if(_baoliaoDictionary && [_baoliaoDictionary isKindOfClass:[NSDictionary class]])
        {
            //如果是电商页面，还有 buyurl2 字段，
            NSString* strBuyurl2 = [[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"buyurl2"]] replaceNullString];
        
            if(strBuyurl2 && strBuyurl2.length > 0)
            {
                //如果有buyurl2，就根据buyurl2数据，获取sku、尺码、颜色、价格、库存等信息
                [self getSkuData: strBuyurl2];
            }
        }
    }
    if ([self.goods_from isEqualToString:@"huojia"]) {
        NSString* strFlag = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('danpin_huojia_buybtn_enable').value"];
        NSLog(@"danpin_huojia_buybtn_enable: %@", strFlag);
        if (strFlag.length>0 && [strFlag intValue]==1) {
            if (_toolView){
                [_toolView EnableBuyButton:YES];
            }
        }else{
            if (_toolView){
                [_toolView EnableBuyButton:NO];}
        }
    }
    return ret;
}

- (BOOL) isDianshangPage
{
  //  NSString* strFlag = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('dp618DATA').type"];
    NSString* strFlag = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('danpin_dianshang_page_flag').value"];
    NSLog(@"danpin_dianshang_page_flag: %@", strFlag);
    if ([self.goods_from isEqualToString:@"huojia"]) {
        NSString* strFlag = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('danpin_huojia_buybtn_enable').value"];
        NSLog(@"danpin_huojia_buybtn_enable: %@", strFlag);
        if (strFlag.length>0 &&[strFlag intValue]==1) {
            if (_toolView) {
                 [_toolView EnableBuyButton:YES];
            }
            
        }else{
            if (_toolView){
              [_toolView EnableBuyButton:NO];
            }
        }
    }
    if(strFlag.length > 0)
    {
        return YES;
    }
    
    return  NO;
}

-(BOOL)isShowBuyTool:(NSString*)urlstr
{
    if (urlstr.length==0) {
        return NO;
    }
    BOOL isShow = NO;
    _buyUrlArray = [ZShare sharedInstance].buyUrlArray;
    for (NSDictionary *obj in _buyUrlArray) {
        NSString *domain = [[NSString stringWithFormat:@"%@",[obj objectForKey:@"domain"]] replaceNullString];
         NSString *name = [[NSString stringWithFormat:@"%@",[obj objectForKey:@"name"]] replaceNullString];
        NSRange foundObj = [urlstr rangeOfString:domain];
        _JSBridge =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"JSBridge_IOS"]] replaceNullString];
        if(foundObj.length>0)
        {
            BOOL ishave = NO;
            id uri = [obj objectForKey:@"uri"];
            if (uri && [uri isKindOfClass:[NSArray class]]) {
                NSArray *tempUri = (NSArray *)uri;
                for (NSString *tag in tempUri)
                {
                    if([tag length] == 0 || [tag isEqualToString:@"*"])
                    {
                        ishave = YES;
                        _orderInfo.webName =name;
                        break;
                    }
                    NSRange foundObj=[urlstr rangeOfString:tag];
                    if(foundObj.length>0)
                    {
                        _orderInfo.webName =name;
                        ishave = YES;
                        break;
                    }
                }
            }
            if (ishave) {
                _orderInfo.webName =name;
                isShow = YES;
                break;
            }
            
        }
    }
 
    return isShow;
}
#pragma mark - 购买逻辑
//=================================================
//购买逻辑
//=================================================
//展示工具栏
-(void)showShopToolView:(NSString *)price
{
    
    if (_shoptoolView) {
        _shoptoolView.actionBlock=nil;
        [_shoptoolView removeFromSuperview];
        _shoptoolView=nil;
    }
    _webView.frame = CGRectMake(0, 60, self.view.bounds.size.width, self.view.bounds.size.height-45-60);
    _shoptoolView =[[ShopToolView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-45, self.view.frame.size.width, 45)];
      __weak typeof (self) wSelf = self;
    [_shoptoolView setCallBack:^(ShopToolEventType type, UIView *v, id k, id va) {
        switch (type) {
            case ShopToolEventType_buy: //展示购买页面
            {
                
                if(wSelf.orderInfo.fTotalPrice>0)
                {
                    if ([wSelf.shoptoolView.priceStr rangeOfString:@"---"].location != NSNotFound) {
                        [[ZToastManager ShardInstance] showtoast:@"正在计算价格，请稍后..."];
                        return;
                    }
                    if ([wSelf isLogin])
                    {
                        //去购买的统计页面
                        
                        NSString *can_buy =[[NSString stringWithFormat:@"%@",[wSelf.baoliaoDictionary objectForKey:@"can_buy"]] replaceNullString] ;
                        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                        [dict setValue:@"buypagebuy" forKey:@"action"];
                        [dict setValue:wSelf.urlstr forKey:@"source"];
                        [dict setValue:wSelf.titlestr forKey:@"type"];
                        [dict setValue:can_buy forKey:@"can_buy"];
                        [BaseModel statbuypage:dict success:^(AFHTTPRequestOperation *operation, id result) {
                            
                        } failure:^(NSError *error) {
                            
                        }];
                        
                        [UMengShare event:CK_GOBUY acc:1];
                        if ([wSelf.titlestr isEqualToString:@"search"]) {
                            [UMengShare event:CK_SEARCHBUY acc:1];
                        }
                        wSelf.orderInfo.webUrl =wSelf.urlstr;
                        OrderViewController *order =[[OrderViewController alloc] init];
                        order.orderInfo = wSelf.orderInfo;
                        order.type =wSelf.titlestr;
                        [wSelf.navigationController pushViewController:order animated:YES];
                        order =nil;
                        
                      
                    }
                    
                }
                else
                {
                    //if(wSelf.timerCheckPrice)
                    if([wSelf isDianshangPage] == YES)
                    {
                        //商品详情界面
                        [[ZToastManager ShardInstance] showtoast:@"请选择尺寸或颜色。"];
                    }
                    else
                    {
                        [[ZToastManager ShardInstance] showtoast:@"这不是商品界面呀！"];
                    }
                }

            }
                break;
            case ShopToolEventType_add: //展示购买页面
            {
                [wSelf addordelQTY:1];
               
            }
                break;
            case ShopToolEventType_del: //展示购买页面
            {
                [wSelf addordelQTY:-1];
            
            }
                break;
            default:
                break;
        }
    }];
    [self.view addSubview:_shoptoolView];

}
-(void)addordelQTY:(int)type
{
    int qty = self.orderInfo.nQty;
    int mqty = self.orderInfo.maxQty;
    
    if (type==1) {
        if (qty>=1) {
            qty++;
        }
        if (qty>mqty) {
            return;
        }
    }else{
        if (qty>1) {
            qty --;
        }else
        {
            return;
        }
    }
    
    self.orderInfo.nQty =qty;
    //todo：
    self.shoptoolView.priceStr = @"---";
    if(_selectQty)
        self.shoptoolView.qtyStr = [NSString stringWithFormat:@"( %d个 △ )",self.orderInfo.nQty];
    else
        self.shoptoolView.qtyStr = [NSString stringWithFormat:@"( %d个 )",self.orderInfo.nQty];
    NSString *jsstr =[NSString stringWithFormat:@"_dp618SetQty('%d')",self.orderInfo.nQty];
    if (jsstr.length==0) {
        return;
    }
    [self.webView stringByEvaluatingJavaScriptFromString:jsstr];
}


//编码图片, 把列表页cell里面的图片传过来， 这样就不用重新从网络上加载同样的图片了。
//todo：关键是怎么把图片传过来呢？
- (NSString *)htmlForJPGImage:(UIImage *)image
{
    NSData *imageData = UIImageJPEGRepresentation(image,1.0);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
    return [NSString stringWithFormat:@"<img src = \"%@\" width=200 style=\"vertical-align:middle;\" />", imageSource];
}
//=====================
//用户认证
//=====================
-(BOOL)isLogin
{
    if ([[ZShare sharedInstance] isLogin]) {
        return YES;
    }else
    {
        UserNavigationController *viewcontroller =[UserNavigationController newWithCameraDelegate:self];
        [self presentViewController:viewcontroller animated:NO completion:nil];
        
        return NO;
    }
    return NO;
}
-(void)userLoginOK:(id)userinfo
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)userDidCancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//=====================
//事件监听
/*
【danpin协议】
全部评论：danpin:{"action":"commlist","type":"","postid":""}
发表评论：danpin:{"action":"comment","content_object":""}
回复评论: danpin:{"action":"reply","resource_uri":""}
@某人: danpin:{"action":"at","resource_uri":"","nickname":""}
顶、踩、举报：danpin:{"action":"commvote","flag":"","commid":"","resource_uri":""}
全网比货：danpin:{"action":"niubi","words":""}
商品页：danpin:{"action":"viewpost","url":"http://h5.m.danpin.com/test.json"}，相关商品，推荐商品等
个人中心：danpin:{"action":"user","userid":"","nickname":""}，点击网页中的用户头像
直接购买:danpin:{"action":"buy","siteName":"亚马逊美国","skuID":"B00S5HFVGI","cartInfo":"a=B00S5HFVGI&quantity=1","totalPrice":"1171","conversionFee":"35","shipFeeLocal":"0","taxPrice":"96","shipFeeOverseas":"80","price":"960","shippingWeight":"1.2","weightUnit":"磅","dimsInfo":"Black","qty":"1","maxQty":"1","category":"amazon-tablets","title":"Fire HD 8, 8\" HD Display, Wi-Fi, 8 GB - Includes Special Offers, Black","image":"http://ecx.images-amazon.com/images/I/41tgdldYYAL._SY400_.jpg","enable":"1"}
百川购买:danpin:{"action":"baichuan","id":"1111","type":"1","url":"http://taobao"}
喜欢（收藏）：danpin:{"action":"love","content_object" : ""}
关注：danpin:{"action":"follow","username":""}
订阅：danpin:{"action":"subscibe","tag":""}
 */
//=====================
-(void)parserURLScheme:(NSURLRequest *)request webView:(UIWebView*)webView
{
    if (![request.URL.scheme isEqualToString:@"danpin"]) {
        return;
    }
    NSString *params = request.URL.resourceSpecifier;
    if (params.length>0) {
        params = [params stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:[params dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        if (!_jsDictionary) {
            _jsDictionary =[[NSMutableDictionary alloc] init];
        }
        _jsDictionary = [NSMutableDictionary dictionaryWithDictionary:dcRes];
        //
        NSString *action =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"action"]] replaceNullString];
        if ([action isEqualToString:@"niubi"]) //比价
        {
            NSString *wrod =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"words"]] replaceNullString];
            NiubiSearchVC *search =[[NiubiSearchVC alloc] init];
            search.strSearchTerm = wrod;//自动搜索 word
            [self.navigationController pushViewController:search animated:NO];
            return;
        }
        else if ([action isEqualToString:@"viewpost"]) //相关商品
        {
            NSString *urlstr =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"url"]] replaceNullString];
            if (urlstr.length > 0)
            {
                WebViewController *shaidanweb =[[WebViewController alloc] init];
                shaidanweb.titlestr =[NSString stringWithFormat:@"%@_xiangguan",_titlestr];
                shaidanweb.jsonUrl =urlstr;
                 shaidanweb.shareDictionary =self.shareDictionary;
                [self.navigationController pushViewController:shaidanweb animated:YES];
                shaidanweb=nil;
            }
            
        }
        else if ([action isEqualToString:@"commlist"]) //全部评论：danpin:{"action":"commlist","type":"","postid":""}
        {
            NSString *postid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"postid"]] replaceNullString];
            JSCommentViewController *jscomment = [[JSCommentViewController alloc] init];
            jscomment.commentId =postid;
            jscomment.content_object =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"resource_uri"]] replaceNullString];
            [self.navigationController pushViewController:jscomment animated:YES];
            jscomment=nil;
            return;
        }else if ([action isEqualToString:@"comment"]) //发表评论：danpin:{"action":"comment","type":"","postid":"","resource_uri":""}
        {
            if ([self isLogin]) {
                _commentFrom=1;
                [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
            }
            
            return;
        }else if ([action isEqualToString:@"reply"]) //回复评论: danpin:{"action":"reply","type":"","postid":"","commid":"","resource_uri":""}
        {
            if ([self isLogin]) {
                _commentFrom=2;
                [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
            }
            return;
        }else if ([action isEqualToString:@"at"]) //@某人: danpin:{"action":"at","type":"","postid":"","nickname":"","resource_uri":""}
        {
             NSString *nickname =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"nickname"]] replaceNullString];
            if ([self isLogin]) {
                _commentFrom=3;
                [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
                NSString *name =[NSString stringWithFormat:@"@%@ ", nickname];
                [CommentKeyBord commentKeyboard].mTextView.text = name;
            }
            return;
        }else if ([action isEqualToString:@"commvote"]) //顶、踩、举报：danpin:{"action":"commvote","flag":"","commid":""}
        {
             NSString *flag =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"flag"]] replaceNullString];
             NSString *commid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"commid"]] replaceNullString];
             NSString *resource_uri =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"resource_uri"]] replaceNullString];
            
            if ([self isLogin]) {
                [self dingcaijubao:flag commentId:commid resource_uri:resource_uri];
            }
            return;
        }else if([action isEqualToString:@"love"])// 喜欢（收藏）：danpin:{"action":"love","type":"","postid":"","resource_uri":""}
        {
            if ([self isLogin]) {
                NSString *postid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"postid"]] replaceNullString];
                NSString *resource_uri =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"resource_uri"]] replaceNullString];
                [self likeWithPid:postid resource_uri:resource_uri];
            }
        }else if ([action isEqualToString:@"user"]) //个人中心：danpin:{"action":"user","userid":""}，点击网页中的用户头像
        {
            NSString *userid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"userid"]] replaceNullString];
            NSString *largeFace =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"largeFace"]] replaceNullString];
            NSString *nick_name =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"nickname"]] replaceNullString];
            
            OtherUserCenterVC *user =[[OtherUserCenterVC alloc] init];
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:[NSString stringWithFormat:@"%@",largeFace] forKey:@"largeFace"];
            [dict setValue:[NSString stringWithFormat:@"%@",userid] forKey:@"user_id"];
            [dict setValue:[NSString stringWithFormat:@"%@",nick_name] forKey:@"nick_name"];
            user.userDictionary=dict;
            [self.navigationController pushViewController:user animated:YES];
           return;
        }else if ([action isEqualToString:@"baichuan"]) //百川购买:danpin:{"action":"baichuan","id":"1111","type":"1","url":"http://taobao"}
        {
            //todo: 这种方式只是展示了html5页面而已，根本不是利用native app打开的淘宝，意义不大。
            NSString *bid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"id"]] replaceNullString];
            NSString *type =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"type"]] replaceNullString];
            if (bid.length>0) {
                [UMengShare event:CK_BUYBAICHUAN acc:1];
                [[BaiChuanShare sharedInstance] showTaoKeItemDetail:self ItemId:bid itemType:type];
                return;
            }else{
                NSString *link =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"url"]] replaceNullString];
                if (link.length>0) {
                    [UMengShare event:CK_BUYBAICHUAN acc:1];
                    [[BaiChuanShare sharedInstance] showPage:self isNeedPush:YES openUrl:link];
                }
            }
            return;
        }else if ([action isEqualToString:@"buy"]) //直接下单
        {
            //danpin:{"action":"buy","siteName":"亚马逊美国","skuID":"B00S5HFVGI","cartInfo":"a=B00S5HFVGI&quantity=1","totalPrice":"1171","conversionFee":"35","shipFeeLocal":"0","taxPrice":"96","shipFeeOverseas":"80","price":"960","shippingWeight":"1.2","weightUnit":"磅","dimsInfo":"Black","qty":"1","maxQty":"1","category":"amazon-tablets","title":"Fire HD 8, 8\" HD Display, Wi-Fi, 8 GB - Includes Special Offers, Black","image":"http://ecx.images-amazon.com/images/I/41tgdldYYAL._SY400_.jpg","enable":"1"}
            if ([self isLogin]) {
                OrderInfo *orderinfo =[[OrderInfo alloc] init];
                orderinfo.webName = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"siteName"]] replaceNullString];
                orderinfo.strSkuID = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"skuID"]] replaceNullString];
                orderinfo.strPa = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"cartInfo"]] replaceNullString];
                orderinfo.fTotalPrice = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"totalPrice"]] replaceNullString] floatValue];
                orderinfo.conversionFee = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"conversionFee"]] replaceNullString] floatValue];
                orderinfo.fFareFee = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"shipFeeLocal"]] replaceNullString] floatValue];
                orderinfo.taxPrice = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"taxPrice"]] replaceNullString] floatValue];
                orderinfo.fFareFeeUSA = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"shipFeeOverseas"]] replaceNullString] floatValue];
                orderinfo.fPrice = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"price"]] replaceNullString] floatValue];
                orderinfo.fPounds = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"shippingWeight"]] replaceNullString] floatValue];
                orderinfo.strWeightUnit = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"weightUnit"]] replaceNullString];
                orderinfo.strDim = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"dimsInfo"]] replaceNullString];
                orderinfo.nQty = [[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"qty"]] replaceNullString] intValue];
                orderinfo.strProduct = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"title"]] replaceNullString];
                orderinfo.strProductImageURL = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"image"]] replaceNullString];
                NSString *buyUrl =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"money_url"]] replaceNullString] ;
                orderinfo.webUrl = buyUrl;
                orderinfo.strJson =[ZShare DataTOjsonString:dcRes];
                
                NSString *coupon =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"coupon"]] replaceNullString];
                [ZShare sharedInstance].zhekouquan = coupon;
                OrderViewController *orderview =[[OrderViewController alloc] init];
                orderview.orderInfo = orderinfo;
                orderview.type = [NSString stringWithFormat:@"%@_action_buy",_titlestr];
                [self.navigationController pushViewController:orderview animated:YES];
                orderview=nil;
            }
          
        }else if ([action isEqualToString:@"follow"])//关注：danpin:{"action":"follow","username":"","userid":""}
        {
             NSString *userid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"userid"]] replaceNullString];
             NSString *username =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"username"]] replaceNullString];
            if ([self isLogin]){
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:@"follow_user" forKey:@"action"];
                [dict setValue:@"" forKey:@"brand_id"];
                [dict setValue:@"" forKey:@"cate_id"];
                [dict setValue:userid forKey:@"follow_id"];
                [dict setValue:username forKey:@"follow_name"];
                [dict setValue:@"" forKey:@"tag"];
                [BaseModel follow:dict success:^(AFHTTPRequestOperation* operation, id result){
                    
                    if (result&&[result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultDist =(NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                    }
                    
                } failure:^(NSError* error){
                    [[ZToastManager ShardInstance] showtoast:@"取消关注失败"];
                }];
            }
        }
        else if ([action isEqualToString:@"subscribe"]) //订阅：danpin:{"action":"subscribe","category":"",resource_uri:""}
        {
            NSString *resource_uri =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"resource_uri"]] replaceNullString];
            NSString *category =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"category"]] replaceNullString];
            if ([self isLogin]) {
                [self subscibeResource_uri:resource_uri name:category];
            }
        }
        /*货架协议
         */
        else if ([action isEqualToString:@"viewdpspu"])
        {// 商品页：danpin:{"action":"viewdpspu","spuid":"1015967","url":"api.test1.danpin.com/v2/viewspu.php?spuid=1015967"}，相关商品，推荐商品等
            NSString *urlstr =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"url"]] replaceNullString];
            if (urlstr.length > 0)
            {
                WebViewController *shaidanweb =[[WebViewController alloc] init];
                shaidanweb.titlestr =[NSString stringWithFormat:@"%@_huojia",_titlestr];
                shaidanweb.jsonUrl =urlstr;
                shaidanweb.shareDictionary =self.shareDictionary;
                [self.navigationController pushViewController:shaidanweb animated:YES];
                shaidanweb=nil;
            }
        }else if ([action isEqualToString:@"lovedpspu"])
        {// 喜欢（收藏）：danpin:{"action":"lovedpspu","spuid":"1015967"}
            //喜欢
            NSString *spuid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"spuid"]] replaceNullString];
            if(spuid.length>0)
            {
                [UMengShare event:CK_LOVE acc:1];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:spuid forKey:@"photo_id"];
                [BaseModel love:dict success:^(AFHTTPRequestOperation *operation, id result) {
                    int code =  [[result objectForKey:@"code"] intValue];
                    if (code==1) {
                        _toolView.isLove = YES;
                    }else
                    {
                        _toolView.isLove = NO;
                    }
                    
                } failure:^(NSError *error) {
                    _toolView.isLove = NO;
                }];
            }
        }else if ([action isEqualToString:@"commlistdpspu"])
        {// 全部评论：danpin:{"action":"commlistdpspu","spuid":"1015967"}
            NSString *spuid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"spuid"]] replaceNullString];
            if (spuid.length>0) {
                StorageCommentViewController *comm =[[StorageCommentViewController alloc] init];
                comm.commentId =spuid;
                [self.navigationController pushViewController:comm animated:YES];
                comm=nil;
                return;
            }
          
        }else if ([action isEqualToString:@"commentdpspu"])
        {//发表评论：danpin:{"action":"commentdpspu","spuid":"1015967"}
           
            if ([self isLogin]) {
                _commentFrom=1;
                [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
            }
        }else if ([action isEqualToString:@"replydpspu"])
        {// 回复评论: danpin:{"action":"replydpspu","spuid":"","commid":""}
             NSString *spuid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"spuid"]] replaceNullString];
             NSString *commid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"commid"]] replaceNullString];
            if ([self isLogin]) {
                _commentFrom=4;
                self.photo_id = spuid;
                self.comment_id =commid;
                [[CommentKeyBord commentKeyboard] textViewShowView:self commentKeyboardDelegate:self];
            }
        }else if ([action isEqualToString:@"atdpspu"])
        {// @某人: danpin:{"action":"atdpspu","spuid":"","nickname":""}
            
        }else if ([action isEqualToString:@"commvotedpspu"])
        {//顶、踩、举报：danpin:{"action":"commvotedpspu","flag":"","commid":""}，1-顶,-1-踩,-2-举报
           NSString *flag =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"flag"]] replaceNullString];
           NSString *commid =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"commid"]] replaceNullString];
            if ([self isLogin])
            {
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                if ([flag intValue]==1) {
                    [dict setValue:@"push_top" forKey:@"action"];
                }else if([flag intValue]==-1)
                {
                    [dict setValue:@"push_bottom" forKey:@"action"];
                }
                [dict setValue:commid forKey:@"comment_id"];
                [dict setValue:@"" forKey:@"photo_id"];
                [dict setValue:@"" forKey:@"text"];
                
                __weak typeof (self) wSelf = self;
                [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, id result) {
                    if (result==nil) {
                        return ;
                    }
                    if ([result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultt = (NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:[result objectForKey:@"msg"]];
                        id  comment_js =[resultt objectForKey:@"comment_js"];
                        if (comment_js && [comment_js isKindOfClass:[NSString class]])
                        {
                            [wSelf.webView stringByEvaluatingJavaScriptFromString:comment_js];
                        }
                    }
                } failure:^(NSError *error) {
                    [[ZToastManager ShardInstance] showtoast:@"顶踩失败"];
                }];
            }
            
        
        }else if ([action isEqualToString:@"shoplist"])
        {
           // danpin:{"action":"shoplist","cate1":"1000002","cate2":"0","cate3":"0","brand":"0","sort":"newest"}
              NSString *cate1 =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"cate1"]] replaceNullString];
              NSString *cate2 =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"cate2"]] replaceNullString];
              NSString *cate3 =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"cate3"]] replaceNullString];
              NSString *brand =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"brand"]] replaceNullString];
              NSString *sort =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"sort"]] replaceNullString];
            NSString *title =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"title"]] replaceNullString];
            StorageCategoryViewController *category =[[StorageCategoryViewController alloc] init];
            category.navtitle = title;
            category.currentCategory1 = cate1;
            category.currentCategory2 = cate2;
            category.currentCategory3 = cate3;
            category.currentBrand = brand;
            category.currentSort = sort;
            [self.navigationController pushViewController:category animated:YES];
            category=nil;
            
        }else if ([action isEqualToString:@"shaidan"])
        {// @某人: danpin:{action = shaidan;"brand_id" = 83748; "brand_name" = Nike; spuid = 1016006; title = "Nike Thea Premium Sneaker";}
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"title"] ]replaceNullString] forKey:@"title"];
            [dict setValue:[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"group_id"] ]replaceNullString] forKey:@"group_id"];
            [dict setValue:[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"group_name"] ]replaceNullString] forKey:@"group_name"];
            [dict setValue:[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"brand_id"] ]replaceNullString] forKey:@"brand_id"];
            [dict setValue:[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"brand_name"] ]replaceNullString] forKey:@"brand_name"];
            [dict setValue:[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"spuid"] ]replaceNullString] forKey:@"photo_id"];
            ShaiDanVC *shaidanVC =[[ShaiDanVC alloc] init];
            shaidanVC.type=2;
            shaidanVC.cateDictionary = dict;
            [self.navigationController pushViewController:shaidanVC animated:YES];
            shaidanVC=nil;
            return;
        }
        
    }
}
-(void)subscibeResource_uri:(NSString*)resource_uri name:(NSString*)name
{
    __weak typeof (self) wSelf = self;
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilesubscribe/?api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setValue:resource_uri forKey:@"entry"];
    NSString *params = [ZShare DataTOjsonString:param];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        //设置参数
        NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //
        
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
                id  comment_js =[dcRes objectForKey:@"comment_js"];
                if (comment_js && [comment_js isKindOfClass:[NSString class]]) {
                    [wSelf.webView stringByEvaluatingJavaScriptFromString:comment_js];
                }
                if (name.length>0) {
                    NSMutableArray *array = [NSMutableArray arrayWithArray:[ZShare sharedInstance].manuallySubscribe];
                    if (![array containsObject:name]) {
                        [array addObject:name];
                    }
                    [[ZShare sharedInstance] setManuallySubscribe:array];
                }
             
                [[NSNotificationCenter defaultCenter] postNotificationName:@"subscribe" object:nil];
                
            });
        }];
    });
}

-(void)sendBtnClick:(UITextView *)textViewGet
{
    NSLog(@"textViewGet.text=====>%@",textViewGet.text);
    if (textViewGet.text.length==0) {
        return;
    }
    switch (_commentFrom) {
        case 1:
        {
            NSString*postid =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"id"]] replaceNullString];
            NSString*goods_from =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"goods_from"]] replaceNullString];
            
            if ([goods_from isEqualToString:@"huojia"]) {
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:@"comment" forKey:@"action"];
                [dict setValue:@"" forKey:@"comment_id"];
                [dict setValue:@"" forKey:@"good_id"];
                [dict setValue:postid forKey:@"photo_id"];
                [dict setValue:textViewGet.text forKey:@"text"];
                
                __weak typeof (self) wSelf = self;
                [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
                    wSelf.comment_id =@"";
                    if (result==nil) {
                        return ;
                    }
                    if ([result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultt = (NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:@"评论成功！"];
                        NSString *comment_count =[[NSString stringWithFormat:@"%@",[resultt objectForKey:@"comment_count"]] replaceNullString];
                        if ([comment_count intValue]>0) {
                            _toolView.commentCount = comment_count;
                        }
                        
                        id  comment_js =[resultt objectForKey:@"comment_js"];
                        if (comment_js && [comment_js isKindOfClass:[NSString class]])
                        {
                            [wSelf.webView stringByEvaluatingJavaScriptFromString:comment_js];
                        }
                    }
                } failure:^(NSError *error) {
                    [[ZToastManager ShardInstance] showtoast:@"点评失败"];
                }];
            }else{
                [self commentWithPostId:postid commentId:@"" context:textViewGet.text];
            }
        }
            break;
        case 2:
        {
            NSString *pid =[[NSString stringWithFormat:@"%@",[_jsDictionary objectForKey:@"postid"]] replaceNullString];
            NSString *cid =[[NSString stringWithFormat:@"%@",[_jsDictionary objectForKey:@"resource_uri"]] replaceNullString];
            [self commentWithPostId:pid commentId:cid context:textViewGet.text];
            
        }
            break;
        case 3:
        {
            NSString *pid =[[NSString stringWithFormat:@"%@",[_jsDictionary objectForKey:@"postid"]] replaceNullString];
            NSString *cid =[[NSString stringWithFormat:@"%@",[_jsDictionary objectForKey:@"resource_uri"]] replaceNullString];
            [self commentWithPostId:pid commentId:cid context:textViewGet.text];
            
        }
            break;
        case 4:
        {
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:@"comment" forKey:@"action"];
            [dict setValue:self.comment_id forKey:@"comment_id"];
            [dict setValue:@"" forKey:@"good_id"];
            [dict setValue:self.photo_id forKey:@"photo_id"];
            [dict setValue:textViewGet.text forKey:@"text"];
            
            __weak typeof (self) wSelf = self;
            [BaseModel comment:dict success:^(AFHTTPRequestOperation *operation, NSObject *result) {
                wSelf.comment_id =@"";
                wSelf.photo_id =@"";
                if (result==nil) {
                    return ;
                }
                if ([result isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *resultt = (NSDictionary*)result;
                    [[ZToastManager ShardInstance] showtoast:@"回复成功！"];
                    NSString *comment_count =[[NSString stringWithFormat:@"%@",[resultt objectForKey:@"comment_count"]] replaceNullString];
                    if ([comment_count intValue]>0) {
                        _toolView.commentCount = comment_count;
                    }
                    
                    id  comment_js =[resultt objectForKey:@"comment_js"];
                    if (comment_js && [comment_js isKindOfClass:[NSString class]])
                    {
                        [wSelf.webView stringByEvaluatingJavaScriptFromString:comment_js];
                    }
                }
            } failure:^(NSError *error) {
                [[ZToastManager ShardInstance] showtoast:@"回复失败"];
            }];
        }
            break;
        default:
            break;
    }
  
}

-(void)commentWithPostId:(NSString*)pid commentId:(NSString*)commit context:(NSString*)content
{
    __weak typeof (self) wSelf = self;
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    NSString *content_object =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"resource_uri"]] replaceNullString];
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilecomment/?api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setValue:content forKey:@"comment"];
    [param setValue:content_object forKey:@"content_object"];
    [param setValue:pid forKey:@"object_pk"];
    if (commit.length>0) {
        [param setValue:commit forKey:@"parent"];
    }
    [param setValue:@"dp" forKey:@"source"];
    [param setValue:@"8c580ca5fbb52de883c7f1b471c923c4355e9932" forKey:@"security_hash"];
    [param setValue:@"1433149751" forKey:@"timestamp"];
    NSString *params = [ZShare DataTOjsonString:param];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        //设置参数
        NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
      
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (dcRes) {
                    [[ZToastManager ShardInstance] showtoast:@"评论成功！"];
                }
                NSString *comment_count =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"comment_count"]] replaceNullString];
                if ([comment_count intValue]>0) {
                    _toolView.commentCount = comment_count;
                }
                
                id  comment_js =[dcRes objectForKey:@"comment_js"];
                if (comment_js && [comment_js isKindOfClass:[NSString class]])
                {
                    [wSelf.webView stringByEvaluatingJavaScriptFromString:comment_js];
                }
            });
            
        }];
        
       
    });
    
}
///=================
/*
 【顶，踩，举报】：后端请求，根据api_key
 V3
 dpapi.mgpyh.com/api/dp/mobilevote/?api_key=&username=
 
 {"target_object": "/api/dp/mobilecomment/595158/", "flag": -2}
 
 flag = 1 ： 顶 flag=-1 : 踩  flag=-2举报
 需要评论ID 同评论*/
//==================
-(void)dingcaijubao:(NSString *)flag commentId:(NSString*)commit resource_uri:(NSString*)resource_uri
{
    __weak typeof (self) wSelf = self;
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilevote/?api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setValue:flag forKey:@"flag"];
    [param setValue:resource_uri forKey:@"target_object"];
    NSString *params = [ZShare DataTOjsonString:param];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        //设置参数
        NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //
        
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
              
                id  comment_js =[dcRes objectForKey:@"comment_js"];
                if (comment_js && [comment_js isKindOfClass:[NSString class]]) {
                    [wSelf.webView stringByEvaluatingJavaScriptFromString:comment_js];
                }
            });
        }];
    });
}
/*
 /api/dp/mobilefavorite/?api_key=9bcd8d755611c84b7a5012dccf657247ff765c27&username=sdfsfsdfs
 {"entry": "/api/dp/mobilepost/179717/" }
 */
-(void)likeWithPid:(NSString*)pid  resource_uri:(NSString*)resource_uri
{
    __weak typeof (self) wSelf = self;
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilefavorite/?api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setValue:resource_uri forKey:@"entry"];
    NSString *params = [ZShare DataTOjsonString:param];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        //设置参数
        NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //
        
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
          
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
                int is_favorited =[[dcRes objectForKey:@"is_favorited"] intValue];
                if (is_favorited==0) {
                    _toolView.isLove = NO;
                }else{
                    _toolView.isLove = YES;
                }
                id  favorite_js =[dcRes objectForKey:@"favorite_js"];
                if (favorite_js && [favorite_js isKindOfClass:[NSString class]]) {
                    [wSelf.webView stringByEvaluatingJavaScriptFromString:favorite_js];
                }
            });
        }];
    });
}
//判断是否一喜欢
-(void)islike
{
    if (![[ZShare sharedInstance] isLogin]) {
        return;
    }
    __weak typeof (self) wSelf = self;
    
    NSString*postid =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"id"]] replaceNullString];
    NSString*goods_from =[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"goods_from"]] replaceNullString];
    if ([goods_from isEqualToString:@"huojia"])
    {
        NSMutableDictionary *param =[NSMutableDictionary dictionary];
        [param setValue:postid forKey:@"photo_id"];
   
        [StorageInfo haveLove:param success:^(AFHTTPRequestOperation *operation, id result) {
            if (result==nil) {
                return ;
            }
            if ([result isKindOfClass:[NSDictionary class]]) {
                int haveLove = [[result objectForKey:@"haveLove"] intValue];
                NSString* commentcount = [[NSString stringWithFormat:@"%@",[result objectForKey:@"comment_count"]] replaceNullString];
                if (commentcount!=nil && [commentcount length]>0 && [commentcount intValue]>0) {
                    _toolView.commentCount = commentcount;
                }
                    if (haveLove==1) {
                        _toolView.isLove = YES;
                    }else
                    {
                        _toolView.isLove = NO;
                    }
                }else
                {
                    _toolView.isLove = NO;
                }
            
        } failure:^(NSError *error) {
            
        }];
    }else{
        NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
        NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
        NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
        NSString * resource_uri=[[NSString stringWithFormat:@"%@",[_baoliaoDictionary objectForKey:@"resource_uri"]] replaceNullString];
        NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilefavorite/?api_key=%@&username=%@&resource_uri=%@",api_key,user_name,resource_uri];
        
        strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[SVHTTPClient sharedClient] cancelAllRequests];
        [[SVHTTPClient sharedClient] GET:strURL parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
         {
             if (urlResponse.statusCode==401) {
                 [[ZToastManager ShardInstance] showtoast:@"用户状态异常，请重新登录！"];
                 [[ZShare sharedInstance] setUserInfo:nil];
                 return ;
             }
             if (response==nil) {
                 return ;
             }
             NSDictionary *ddddd =(NSDictionary *)response;
             if (error==nil && ddddd !=nil && [ddddd isKindOfClass:[NSDictionary class]]) {
                 id objects = [ddddd objectForKey:@"objects"];
                 if (objects && [objects isKindOfClass:[NSArray class]]) {
                     NSArray *tempa =(NSArray *)objects;
                     if (tempa.count>0) {
                         _toolView.isLove = YES;
                     }else
                     {
                         _toolView.isLove = NO;
                     }
                 }else
                 {
                     _toolView.isLove = NO;
                 }
                 
             }else{
             }
         }];
    }
  
    
}


- (void) getSkuData:(NSString*) crawl_url
{
    
    if(self.isSkuRequesting)
    {
        //如果正在请求，就不要再重复请求了
        return;
    }
    
    if([self isSkuDataInserted])
    {
        //不重复获取数据
        return;
    }

    self.isSkuRequesting = YES;
    
    __weak typeof (self) wSelf = self;
    [[SVHTTPClient sharedClient] GET:crawl_url parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
     {
         [wSelf postResultToDanpin:response url:crawl_url];
     }];


}

- (void) postResultToDanpin:(id) response url:(NSString*)strURL
{
    @autoreleasepool
    {
    //    NSString *post_url =[dc objectForKey:@"post_url"];
    //    post_url = [post_url stringByReplacingOccurrencesOfString:@"###keywords###" withString:searchTerm];
        NSString* strResult=@"";
        
        if(response && [response isKindOfClass:[NSData class]])
        {
            strResult = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
        }
        else if(response && [response isKindOfClass:[NSDictionary class]])
        {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:&error];
            if (! jsonData)
            {
                NSLog(@"Got an error: %@", error);
            }
            else
            {
                strResult = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            }
        }
        else {
            strResult =[[NSString alloc] initWithFormat:@"%@",response];//response;
        }
        
        
        //todo：strPostURL 需要服务器来指定
        NSString* strPostURL = @"http://api.danpin.com/postSizeData.php?action=sku";
        
        //
        NSString *urstr =[NSString stringWithFormat:@"%@%@",strPostURL,[ZShare publicParams]];
        urstr = [urstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSString *  strLocationTime=[ZShare nsdateToString:[NSDate date]];
        //        sign=md5(private_key+urlencode(keywords)+uuid+时间戳)
        NSString *sign =[NSString stringWithFormat:@"84Qq8vzB6vM5PsB2%@%@%@",strURL,[ZShare sharedInstance].getUUID,strLocationTime];
        NSString *strMD5 = [ZShare md5:sign];
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: strResult, @"data",
                                strURL, @"url",
                                strMD5, @"sign",//加密后的md5
                                strLocationTime, @"time", nil];
        strResult=nil;
        __weak typeof (self) wSelf = self;
        
        [[SVHTTPClient sharedClient] POST:urstr parameters:params completion:^(id res, NSHTTPURLResponse *urlResponse, NSError *error)
         {
             _isSkuRequesting  = NO;
             if(res == nil) {return ;}
             NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:res options:kNilOptions error:&error];
             if (dcRes && [dcRes isKindOfClass:[NSDictionary class]])
             {
                 NSString *SizeJS =[[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"SizeJS"]] replaceNullString];
                 if(SizeJS.length > 0)
                 {
                     [wSelf insertedSkuDataFlag];
                     //因为不确定服务器返回时间，把js留在timer里执行
                     [wSelf updateSkuData:SizeJS];

                 }
             }

        }];
    }
}


- (void) updateSkuData:(NSString*) strJS
{
    [self.webView stringByEvaluatingJavaScriptFromString:strJS];
}

- (void) insertedSkuDataFlag
{
    [_webView stringByEvaluatingJavaScriptFromString:@"var div = document.createElement('input');"
     "div.id = 'danpin_sku_data_flag';"
     "div.type = 'hidden';"
     "div.value = 'danpin sku data insserted';"
     "document.body.appendChild(div);"];
}


- (BOOL) isSkuDataInserted
{
    //  NSString* strFlag = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('dp618DATA').type"];
    NSString* strFlag = [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('danpin_sku_data_flag').value"];
    NSLog(@"isSkuDataInserted: %@", strFlag);
    
    if(strFlag.length > 0)
    {
        return YES;
    }
    
    return  NO;
}
-(void) setForceNewWindow:(BOOL)forceNewWindow
{
    _ForceNewWindowOpen = forceNewWindow;

}
//=============================
//=============================
-(void)shortlinkparser:(NSString*)linkurl
{
    if (linkurl.length==0 || [linkurl rangeOfString:@"www.mgpyh.com"].location ==NSNotFound ) {
        return;
    }
    if (_shortLinkWebView) {
        _shortLinkWebView.delegate =nil;
        _shortLinkWebView = nil;
    }
    _shortLinkWebView = [[UIWebView alloc] init];
    _shortLinkWebView.delegate =self;
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:linkurl]];
    [_shortLinkWebView loadRequest:request];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //过滤 跳转app事件
    BOOL ret = NO;
    BOOL isHTTPOrLocalFile = [request.URL.scheme isEqualToString:@"http"] ||[request.URL.scheme isEqualToString:@"about"] || [request.URL.scheme isEqualToString:@"https"] || [request.URL.scheme isEqualToString:@"file"];
    if(isHTTPOrLocalFile)
    {
        ret = YES;
    }
    return ret;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//    NSLog(@"====webViewDidFinishLoad===%@",webView.request.URL.absoluteString);
    if( [webView.request.URL.absoluteString hasPrefix:@"http"])
    {
        self.moneyUrl =webView.request.URL.absoluteString;
    }
  
}
@end
